const api = require("../pages/api/http.js")
const config = require("../config.js")

const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 用户注册接口
 */
const registerUser = (user) => {
  console.debug("注册用户信息：", user)
  var that = this
  var param = {
    openId: user.openId
  }
  api.post(config.isUserExistUrl, param).then(res => {
    if (res != 0) {
      console.debug("用户已存在！", res)
      var param = {
        openId: user.openId,
        userName: user.nickName,
        userImgUrl: user.avatarUrl,
        city: user.city,
      }
      api.post(config.updateUserUrl, param).then(res => {
        if (res == 1) {
          console.log("Update user info successfully!")
        } else {
          console.error("Update user info failed!")
        }
      })
      return
    } else {
      var param = {
        openId: user.openId,
        userName: user.nickName,
        userImgUrl: user.avatarUrl,
        city: user.city,
        outStep: 0,
        inStep: 0,
      }
      console.debug("添加新用户：", param)
      api.post(config.addUserUrl, param).then(res => {
        if (res == 1) {
          console.log("用户添加成功！")
        } else {
          console.error("添加用户失败！")
        }
      }).catch(e => {
        console.error(e)
      })
    }
  })
}

module.exports = {
  formatTime: formatTime,
  registerUser: registerUser
}


